package com.piece.core.framework.util.lock;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 资源锁
 */
public class LockUtil {

    private static final ConcurrentHashMap<String, AtomicInteger> lockMap = new ConcurrentHashMap<>();

    public static AtomicInteger getAtomicInteger(String key) {
        if (null == lockMap.get(key)) {
            lockMap.putIfAbsent(key, new AtomicInteger(0));
        }
        lockMap.get(key).incrementAndGet();
        return lockMap.get(key);
    }

    public static void releaseAtomicInteger(String key) {
        if (null != lockMap.get(key)) {
            int source = lockMap.get(key).decrementAndGet();
            if (source <= 0) {
                lockMap.remove(key);
            }
        }
    }
}